package com.thunder.rebot.rebotclient.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.esotericsoftware.kryonet.Client;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.limedia.explorer.centralcontrol.ControlActivity;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.control.MapImageView;
import com.thunder.rebot.rebotclient.entity.LoginMessageBean;
import com.thunder.rebot.rebotclient.entity.MapCenterEntity;
import com.thunder.rebot.rebotclient.entity.MessageBean;
import com.thunder.rebot.rebotclient.entity.ResponseMessageBean;
import com.thunder.rebot.rebotclient.entity.SocketConectState;
import com.thunder.rebot.rebotclient.entity.TaskDots;
import com.thunder.rebot.rebotclient.entity.TaskMessageBean;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.CommonUtils;
import com.thunder.rebot.rebotclient.utils.LogUtil;
import com.thunder.rebot.rebotclient.utils.TRCommonUtil;
import com.ts.robot.socket.TSRobotSocketNative;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TaskActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = TaskActivity.class.getSimpleName();


    @BindView(R.id.fl)
    public FrameLayout fl;

    @BindView(R.id.iv_task)
    public MapImageView ivTask;


    @BindView(R.id.from)
    public Spinner from;

    @BindView(R.id.to)
    public Spinner to;


    @BindView(R.id.et_content)
    public EditText etContent;
    @BindView(R.id.btn_send)
    public Button btnSend;

    private ArrayList<TaskDots> dots;
    private int screenWidth;//屏幕的宽高
    private Gson gson;
    private SharedPreferences sharedPreferences;
    private ArrayList<TextView> textViews;

    private static TSRobotSocketNative mtsRobotSocketNative;

    /*
       获取robot socket native object
        */
    public static void setRobotSocket(TSRobotSocketNative tsRobotSocketNative){
        mtsRobotSocketNative = tsRobotSocketNative;
    }

    @Override
    public void conectState(int code,final String description) {
        switch (code) {
            case 1:
                Gson gson = new Gson();
                final SocketConectState socketConectState = gson.fromJson(description, new TypeToken<SocketConectState>() {
                }.getType());

                switch (Integer.valueOf(socketConectState.getCode())) {
                    case 10://连接成功
                        ClientUtils.robotConnectFlag = true;
                        break;
                    case 9://连接断开
                        ClientUtils.robotConnectFlag = false;

                        break;
                    case 8://未连接成功
                        ClientUtils.robotConnectFlag = false;
                        break;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(TaskActivity.this, socketConectState.getDescription(), Toast.LENGTH_SHORT).show();
                    }
                });

                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        ButterKnife.bind(this);

        initView();

        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
//        mtsRobotSocketNative = TSRobotSocketNative.getTsRobotSocketNativeInstance();
        mtsRobotSocketNative.addSocketLisetnerInterface(this);
        initData();
        if(getTaskDots() != null){
            gson = new Gson();
            dots = gson.fromJson(getTaskDots(),new TypeToken<ArrayList<TaskDots>>() {}.getType());
        }
        addView();
    }

/*
读取本地存储
 */

    private String getTaskDots(){
        sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        return sharedPreferences.getString("taskdots",null);
    }
    private void addView() {
        if(dots == null) {
            dots = new ArrayList<>();
        }
        TaskDots td1 = new TaskDots();
        td1.setId("1");
        td1.setName("1");
        td1.setX(1.0f);
        td1.setY(1.0f);

        TaskDots td2 = new TaskDots();
        td2.setId("2");
        td2.setName("2");

        td2.setX(3.0f);
        td2.setY(1.0f);


        TaskDots td3 = new TaskDots();
        td3.setId("3");
        td3.setName("3");
        td3.setX(4);
        td3.setY(3);

        TaskDots td4 = new TaskDots();
        td4.setId("4");
        td4.setName("4");
        td4.setX(1);
        td4.setY(3);
        dots.add(td1);
        dots.add(td2);
        dots.add(td3);
        dots.add(td4);
        int i = 0;
        textViews = new ArrayList<>();
        for (final TaskDots td : dots){
            TextView tvIcon1 = new TextView(this);
            tvIcon1.setTextColor(this.getResources().getColor(R.color.blue));
            tvIcon1.setHeight(10);
            tvIcon1.setWidth(1000);
            tvIcon1.setLongClickable(true);
            tvIcon1.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    //弹出dialog
                    alertDialog(td.getName());
                    return false;
                }
            });
            tvIcon1.setText(td1.getName()+"00");
            tvIcon1.setBackground(this.getResources().getDrawable(R.drawable.weizhi_2));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(100,
                    80);
            lp.setMargins(screenWidth/2 + new Double(td.getX() /0.05 * (screenWidth /384)).intValue() - 50 ,
                    new Double(mce.getyPix()/2).intValue() - new Double(td.getY()/0.05 * (mce.getyPix() /384)).intValue() - 40,
                    screenWidth/2 - new Double(td.getX()/0.05 * screenWidth /384).intValue() + 50 ,
                    new Double( mce.getyPix()/2 + td.getY()/0.05 * (mce.getyPix() /384) + 40).intValue());

            textViews.add(tvIcon1);
            fl.addView(tvIcon1, lp);
        }

    }
private void alertDialog(String name){
    new AlertDialog.Builder(this)
            .setTitle("任务的起点")
            .setIcon(android.R.drawable.ic_dialog_info)
//                .setView(edt)
            .setMessage(name )
            .setCancelable(true)
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
//                        Toast.makeText(RegisterActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
//                    if(isClick){
//
//                    }else{
//
//                    }
                }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .show();
}
    private void initData() {
        mce = CommonUtils.getMapCenter(ivTask);
        Log.i(TAG,"@@WP:" + mce.getxPix() + "--" + mce.getyPix());
    }
    private MapCenterEntity mce;
    String fromTask;
    String toTask;
    private int startFrom = 0;
    private int endTo = 0;
    private boolean isClick = false;//选择的是起点还是终点
    private AlertDialog alertDialog;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0://起点
                    //设置字体的颜色
                    for (TextView tv : textViews){
                            tv.setTextColor(TaskActivity.this.getResources().getColor(R.color.blue));
                    }
                    textViews.get(msg.arg2).setTextColor(TaskActivity.this.getResources().getColor(R.color.green));
                    textViews.get(endTo).setTextColor(TaskActivity.this.getResources().getColor(R.color.red));

                    break;
                case 1://终点

                    for (TextView tv : textViews){
                            tv.setTextColor(TaskActivity.this.getResources().getColor(R.color.blue));
                    }
                    textViews.get(msg.arg2).setTextColor(TaskActivity.this.getResources().getColor(R.color.red));
                    textViews.get(startFrom).setTextColor(TaskActivity.this.getResources().getColor(R.color.green));
                    break;
            }
        }
    };

    private void initView() {
        btnSend.setOnClickListener(this);
        ArrayAdapter<CharSequence> adapterfrom = ArrayAdapter.createFromResource(this, R.array.locations, android.R.layout.simple_spinner_item);
        adapterfrom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        from.setAdapter(adapterfrom);  //为下拉列表设置监听
        from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                fromTask = TaskActivity.this.getResources().getStringArray(R.array.locations)[arg2];//获取选择的item内容
                isClick = true;
                startFrom = arg2;
                Message msg = handler.obtainMessage();
                msg.arg1 = 0;
                msg.arg2 = arg2;
                handler.sendMessage(msg);
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub
            }
        });

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(TaskActivity.this, R.array.locations, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        to.setAdapter(adapter);  //为下拉列表设置监听
        to.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                toTask = TaskActivity.this.getResources().getStringArray(R.array.locations)[arg2];//获取选择的item内容
                isClick = true;
                endTo = arg2;
                Message msg = handler.obtainMessage();
                msg.arg1 = 1;
                msg.arg2 = arg2;
                handler.sendMessage(msg);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub
            }
        });

    }


//    @Override
//    public void operateConfirm(Object o) {
//        super.operateConfirm(o);
//        else if(o instanceof MessageBean){
//            switch (((MessageBean) o).getFRAME()){
//                case TSRobotSocketNative.OPERATIONCHECK://"1009"://动作的回复
////                    MessageBean messageBean = new MessageBean();
////                    messageBean.setFRAME("1005");
////                    messageBean.setID(  ((MessageBean) o).getID());
//                    switch (((MessageBean) o).getID())
//                    alert("动作再次确认？",messageBean.getFRAME(),messageBean);
//                    break;
//
//            }
//        }
//    }


    @Override
    public void taskConfirm(Object o) {
        super.taskConfirm(o);
        if(o instanceof ResponseMessageBean){
            ResponseMessageBean responseMessageBean = (ResponseMessageBean) o;
            switch (responseMessageBean.getFRAME()){
                case TSRobotSocketNative.OPERATIONCHECK://"1009"://任务回复
                    Log.d(TAG, "@@wp:" + responseMessageBean.toString());
                    tips(responseMessageBean);
                    break;
            }
        }
    }
    private void tips(ResponseMessageBean responseMessageBean){
            switch (responseMessageBean.getFRAME()){
                case TSRobotSocketNative.OPERATIONCHECK://"1009"://任务回复
                    if(responseMessageBean.getRESPOND().equals("-1")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TaskActivity.this, "任务发送失败,请重新发布",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else if (responseMessageBean.getRESPOND().equals("0")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TaskActivity.this, "任务发送已经成功，并保存在队列中",Toast.LENGTH_SHORT).show();
                            }
                        });
                        TaskActivity.this.finish();
                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TaskActivity.this, "任务发送成功，并立即执行",Toast.LENGTH_SHORT).show();
                            }
                        });
                        TaskActivity.this.finish();
                    }

                    break;
            }
    }


    private void alert(String content ,final ResponseMessageBean responseMessageBean){
        if (alertDialog != null && alertDialog.isShowing()){return;}
        Looper.prepare();
        alertDialog = new AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setIcon(android.R.drawable.ic_dialog_info)
//                .setView(edt)
                .setMessage("" +content)
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        if (ClientUtils.connectFlag) {

                            switch (responseMessageBean.getFRAME()){
                                case TSRobotSocketNative.OPERATIONCHECK://"1009"://任务回复
                                    if(responseMessageBean.getRESPOND().equals("-1")){
                                        alert("任务发送失败,请重新发布",responseMessageBean);
                                    }else if (responseMessageBean.getRESPOND().equals("0")){
                                        alert("任务发送已经成功，并保存在队列中",responseMessageBean);
//                                        TaskActivity.this.finish();
                                    }else{
                                        alert("任务发送成功，并立即执行",responseMessageBean);
//                                        TaskActivity.this.finish();
                                    }

                                    break;
                            }
                            if(alertDialog.isShowing()) {
                                alertDialog.dismiss();
                            }

                        } else {
                            Looper.prepare();
                            Toast.makeText(TaskActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    }
                })
                .show();
        Looper.loop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_send:
                if(startFrom == endTo && TextUtils.isEmpty(etContent.getText().toString().trim())){
                    Toast.makeText(TaskActivity.this, "任务描述不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                /*

                 */
                String name = sharedPreferences.getString("username",null);
                if(TextUtils.isEmpty(name)){
                    return;
                }
                String start = TaskActivity.this.getResources().getStringArray(R.array.locations)[startFrom];
                String end = TaskActivity.this.getResources().getStringArray(R.array.locations)[endTo];
                //开始发送任务

                final TaskMessageBean tmb = new TaskMessageBean();
                tmb.setID(name);
                tmb.setFROM(start);
                tmb.setTO(end);
                tmb.setFRAME("1003");
                tmb.setTXT("拿一张港币");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mtsRobotSocketNative.send_data_native(new Gson().toJson(tmb));
//                        LoginMessageBean loginMessageBean = new LoginMessageBean();
//                        loginMessageBean.setFRAME("1001");
//                        loginMessageBean.setID("1");
//                        loginMessageBean.setPW("1");
//                        Gson gson = new Gson();
//                        Log.d(TAG,"login:" + gson.toJson(loginMessageBean));
//                        mtsRobotSocketNative.send_data_native(gson.toJson(loginMessageBean));
                    }
                }).start();
//                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mtsRobotSocketNative.removeSocketLisetnerInterface(this);
    }
}
